<?php

class UserController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',
				'actions'=>array('register','activate'),
				'users'=>array('*'),
			),
			array('deny', // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Default action.
	 * @throws CHttpException when called
	 */
	public function actionIndex()
	{
		throw new CHttpException(404,Yii::t('frontend','The page your requested could not be found.'));
	}

	/**
	 * Displays the register page
	 */
	public function actionRegister()
	{
		$model = new RegisterForm();

		if (isset($_POST['ajax']) && $_POST['ajax'] === 'register-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		if (isset($_POST['RegisterForm']))
		{
			$model->attributes = $_POST['RegisterForm'];
			if ($model->validate())
			{
				$user = new User();
				$user->name = $model->email;
				$user->email = $model->email;
				$user->password = $model->password;
				$user->status = User::STATUS_UNACTIVATED;
				$user->save(false);

				$activation = new UserActivation();
				$activation->userId = $user->id;
				$activation->email = $user->email;
				$activation->code = md5(uniqid('', true));
				$activation->save(false);

				/** @var $mailer PhpMailer */
				$mailer = Yii::app()->mailer;
				$mailer->CharSet = Yii::app()->charset;
				$mailer->From = Yii::app()->params['systemEmail'];
				$mailer->FromName = 'Kuvakilpailut.net';
				$mailer->AddAddress($model->email);
				$mailer->Subject = Yii::t('email','Welcome to Kuvakilpailut.net');
				$mailer->getView('_activation',array(
					'activationUrl'=>Yii::app()->createAbsoluteUrl('/user/activate',array('email'=>$model->email,'code'=>$activation->code)),
				));
				$mailer->isHTML(true);
				$mailer->Send();

				Yii::app()->user->setFlash(WebUser::FLASH_INFO,Yii::t('flash','Thank you for registering! You will shortly receive an activation e-mail.'));
				$this->redirect(Yii::app()->homeUrl);
			}
		}

		$this->render('register',array('model'=>$model));
	}

	/**
	 * Activates a specific user.
	 * @param $email the user e-mail address
	 * @param $code the activation code
	 */
	public function actionActivate($email, $code)
	{
		$activation = UserActivation::model()->findByAttributes(array(
			'email'=>$email,
			'code'=>$code,
		));

		if ($activation !== null)
		{
			$user = $this->loadModel($activation->userId);
			$user->status = User::STATUS_ACTIVATED;
			$user->save(false);

			$activation->delete();

			$identity = new UserIdentity($user->name, $user->password);
			$identity->authenticate(UserIdentity::AUTH_TYPE_ACTIVATION);

			if ($identity->errorCode === UserIdentity::ERROR_NONE)
			{
				$duration = 3600 * 24 * 30; // 30 days
				Yii::app()->user->login($identity, $duration);
			}

			Yii::app()->user->setFlash(WebUser::FLASH_SUCCESS, Yii::t('flash','Account activated.'));
		}
		else
		{
			Yii::app()->user->setFlash(WebUser::FLASH_ERROR, Yii::t('flash','Account activation failed!'));
		}

		$this->redirect(Yii::app()->homeUrl);
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the model
	 */
	public function loadModel($id)
	{
		$model = User::model()->findByPk($id);
		if ($model === null)
			throw new CHttpException(404,'The requested page does not exist.');
		
		return $model;
	}
}
